package com.mradio.app.model.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.mradio.app.model.NewMessageModel;

public class NewMessageModelValidator implements Validator {

	/** Logger. */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public boolean supports(Class<?> arg0) {
		return NewMessageModel.class.isAssignableFrom(arg0);
	}

	/**
	 * Validates the model for sending a message.
	 * 
	 */
	@Override
	public void validate(Object target, Errors errors) {
		NewMessageModel newMessage = (NewMessageModel) target;
		logger.info("Validating NewMessageModel");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subject", "subject_not_empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "senderEmail", "sender_email_not_empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "message", "message_not_empty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "senderName", "sender_name_not_empty");
		
		Pattern emailPattern = Pattern.compile("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@"
			+ "(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?");
		Matcher matcher = emailPattern.matcher(newMessage.getSenderEmail());
		if (StringUtils.isNotBlank(newMessage.getSenderEmail()) && !matcher.matches()) {
			errors.rejectValue("senderEmail", "sender_email_not_valid");
		}
	}

}
